package com.ccx.myinterpreter;

import java.util.List;
import java.util.Map;

public class LoxClass implements Callable {

    private String name;
    private Map<String, LoxFun> methods;
    private LoxClass superClass;

    public LoxClass(String name, Map<String, LoxFun> methods, LoxClass superClass) {
        this.name = name;
        this.methods = methods;
        this.superClass = superClass;
    }

    public LoxFun findMethod(String name) {
        LoxFun method = methods.get(name);
        if(method == null && superClass != null) {
            method = superClass.findMethod(name);
        }
        return method;
    }
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Map<String, LoxFun> getMethods() {
        return methods;
    }
    public void setMethods(Map<String, LoxFun> methods) {
        this.methods = methods;
    }

    @Override
    public Object call(Interpreter interpreter, List<Object> args) {
        LoxInstance instance = new LoxInstance(this);
        LoxFun initlizer = findMethod("init");
        if(initlizer != null) {
            initlizer.bindThis(instance).call(interpreter, args);
        }
        return instance;
    }

    @Override
    public int arity() {
        LoxFun initlizer = findMethod("init");
        if(initlizer != null) {
            return initlizer.arity();
        }
        return 0;
    }
    
}
